/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.game.math.view.action;

import java.awt.event.ActionEvent;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import org.game.math.config.Configure;
import org.game.math.expression.Operator;

/**
 *
 * @author nmduc
 */
public abstract class DefaultOperatorAction extends AbstractToggleAction implements Observer {

    private Operator operator;

    public DefaultOperatorAction(String name, Operator operator, Configure configure) {
        super(name, configure);
        this.operator = operator;
        this.updateEnable(configure);
        this.updateSelected(configure);
    }

    private void updateEnable(Configure configure) {
        Set<Operator> operators = configure.getOperators();
        this.setEnabled(!configure.isChosenMultiTable() && (operators.size() > 1 || !operators.contains(this.operator)));
    }

    private void updateSelected(Configure configure) {
        Set<Operator> operators = configure.getOperators();
        this.setSelected(operators.contains(this.operator));
    }

    @Override
    public final void actionPerformed(ActionEvent ae) {
        if (this.isSelected()) {
            Configure.getInstance().addOperator(this.operator);
        } else {
            Configure.getInstance().removeOperator(this.operator);
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        Configure configure = (Configure) o;
        this.updateEnable(configure);
    }
}
